package com.atguigu.function;

import com.atguigu.bean.WaterSensor;
import com.google.gson.internal.$Gson$Preconditions;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

public class User_DefinedFunction_Scala {
    public static void main(String[] args) {


        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port",10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration);
        env.setParallelism(2);



        //1、创建表环境
        DataStreamSource<WaterSensor> waterSensorStream =
                env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                        new WaterSensor("sensor_1", 2000L, 20),
                        new WaterSensor("sensor_2", 3000L, 30),
                        new WaterSensor("sensor_1", 4000L, 40),
                        new WaterSensor("sensor_1", 5000L, 50),
                        new WaterSensor("sensor_2", 6000L, 60));
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        Table table = tEnv.fromDataStream(waterSensorStream);
        tEnv.createTemporaryView("sensor", table);

        //1、在tableAPI中自定义函数

        //这里实现一下将小写字母转为大写得函数
        //1、1 使用内联得方式
        table
                .select($("id"),call(MyToUpper.class,$("id")))
                .execute()
                .print();

        //1、2 先注册，然后再使用
        tEnv.createTemporaryFunction("myToUpper",MyToUpper.class);
        table.select($("id"),call("myToUpper",$("id")))
                .execute().print();


        //2、在sql中使用
        tEnv.sqlQuery("select " +
                " id, myToUpper(id) upId" +
                " from sensor ").execute().print();

    }
}
